<!-- @format -->

<!--添加修改用户信息-->
<template>
    <a-modal v-model="showAddTable" :width="640"
             :title="title ? '用户新增' : '用户编辑'"
             :maskClosable="false"
             :destroyOnClose="true" @cancel="cancelApply">
        <a-form :form="form" @keydown.native.enter.prevent="saveApply" class="modelSearch">
            <a-form-item label="用户登录名（学号）" v-bind="formStyle" required>
                <a-input
                        placeholder="请输入用户登录名"
                        :disabled="!title"
                        ref="refocus"
                        v-decorator="[
                        'userName',
                        {
                            rules: [
                                { required: true, message: '请输入英文、数字、@或_字符' },
                                { validator: title?this.verify.validateID3.bind(this):'' }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
                />
            </a-form-item>
            <a-form-item v-bind="formStyle" label="用户姓名" required>
                <a-input
                        placeholder="请输入用户姓名"
                        v-decorator="[
                        'name',
                        {
                            rules: [
                                { required: true, message: '请输入汉字、字母、数字、_或-字符' },
                                { validator: this.verify.validateName.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
                />
            </a-form-item>
            <a-form-item v-bind="formStyle" label="用户性别" required>
              <a-radio-group  v-model="sex"
                              v-decorator="[
                        'sex',
                        {
                            rules: [
                                { required: true,message: '性别不可为空'},
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
              >
                <a-radio value="0">女</a-radio>
                <a-radio value="1">男</a-radio>
              </a-radio-group>
          </a-form-item>
            <a-form-item v-bind="formStyle" label="身份证号">
                <a-input
                        placeholder="请输入身份证号"
                        v-decorator="[
                        'sfzjh',
                        {
                            rules: [
                                { required: false},
                                { validator: this.verify.validateSfz.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
                />
            </a-form-item>
            <a-form-item v-bind="formStyle" label="手机号码" >
                <a-input
                        placeholder="请输入手机号码"
                        v-decorator="[
                        'phoneNum',
                        {
                            rules: [{required: false}, { validator: this.verify.validatePhone.bind(this) }],
                            getValueFromEvent: event => {
                                return event.target.value.replace(/\s/g, '')
                            }
                        }
                    ]"
                ></a-input>
            </a-form-item>
            <a-form-item v-bind="formStyle" label="组织机构" required v-if="perms.sysOrg">
                <a-tree-select
                        style="width: 100%"
                        :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                        :treeData="orgTree"  placeholder="请选择组织机构"
                        v-decorator="['orgId', { rules: [{ required: true, message: '请选择组织机构' }] }]">
                    <span style="color: #08c" slot="title" slot-scope="{key, title}">{{title}}</span>
                </a-tree-select>
            </a-form-item>
            <a-form-item v-bind="formStyle" label="角色" required v-if="perms.addUserRole">
                <a-select
                        placeholder="请选择角色"  :disabled="!title" :showArrow="title"
                        v-decorator="['roleId',  { rules: [{ required: true, message: '请选择角色' }] }]"
                >
                    <a-select-option v-for="item in roleOpts" :value="item.value" :key="item.value">{{ item.label }}</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item v-bind="formStyle" label="登录密码" v-show="title">
                <span style="color:rgba(221,0,0,0.9);">初始化密码为：Cau19121111</span>
            </a-form-item>
        </a-form>
        <div slot="footer">
            <a-button type="default" @click="cancelApply('sysUserDtos')">取消</a-button>
            <a-button type="default" v-if="!title && !isUKeyLogin" @click="resetUserPasswd('sysUserDtos')">重置密码</a-button>
            <a-button type="primary" @click="saveApply">确定</a-button>
        </div>
    </a-modal>
</template>

<script>
import verify from 'libs/verify'

export default {
    name: 'importUser',
    data() {
        return {
            form: this.$form.createForm(this),
            verify,
            showAddTable: false,
            roleType: '',
          sex: '',
            flags: '',
            countOrgChange: 0,
            originalData: {},
            selectedNode: {},
            /*选中的记录*/
            checkData: [],
            orgTreeData: [],
            roleOpts: [],
            isUKeyLogin: sessionStorage.getItem ('isUKeyLogin'),
        }
    },
    computed: {
        formStyle() {
            return this.$store.state.common.formStyle
        }
    },
    props: {
        sysUserDtos: {
            type: Object,
            required: true
        },
        title: {
            type: Boolean,
            required: true
        },
        orgTree: {
            type: Array,
            required: true
        },
        perms: {
            type: Object,
            required: true
        },
        fromRoleOpts: {
            type: Array,
            required: true
        }
    },
    watch: {
        orgTree(value) {
            this.orgTreeData = value
        },
        sysUserDtos(value) {
            this.countOrgChange = 0
            this.selectedNode = {
                id: value.orgId,
                name: value.orgName
            }
        },
        fromRoleOpts: {
            handler(val) {
                this.roleOpts = val
            },
            deep: true,
            immediate: false
        }
    },
    methods: {

        /**
         * Function    : change
         * Description :
         * Input       : val
         * Return      : none
         */
        change(val) {
            let _this = this
            setTimeout(function() {
                if (val) {
                    _this.$refs['refocus'].focus()
                }
            }, 200)
        },

        /**
         * Function    : showModal
         * Description : 打开弹框
         * Input       : none
         * Return      : none
         */
        showModal() {
            this.showAddTable = true
        },

        /**
         * Function    : showEdit
         * Description : 编辑时单位显示
         * Input       : opt单个单位所有数据
         * Return      : none
         */
        showEdit(opt) {
            this.showAddTable = true
            this.id = opt.id
            this.sex = opt.sex
            this.$nextTick(() => {
                this.form.setFieldsValue(this.$pick(opt, ['userName', 'name', 'sfzjh','phoneNum','sex']))
            })
            if(this.perms.sysOrg){
                this.$nextTick(() => {
                    this.form.setFieldsValue(this.$pick(opt, ['orgId']))
                })
            }
            if(this.perms.addUserRole){
                this.$nextTick(() => {
                    this.form.setFieldsValue(this.$pick(opt, ['roleId']))
                })
            }
        },

        /**
         * Function    : saveApply
         * Description : 用户信息新增、编辑保存
         * Input       : name
         * Return      : none
         */
        saveApply(e) {
            e.preventDefault()
            this.form.validateFields((err, value) => {
                if (!err) {
                    this.sysUserDtos.userName = value.userName
                    this.sysUserDtos.name = value.name
                    this.sysUserDtos.sfzjh = value.sfzjh
                    this.sysUserDtos.phoneNum = value.phoneNum
                    this.sysUserDtos.roleId = value.roleId
                    this.sysUserDtos.sex = this.sex
                    if (this.title) {
                        this.sysUserDtos.orgId = value.orgId
                        let para = Object.assign({}, this.sysUserDtos)
                        this.$parent.spinning = true
                        this.$store.dispatch('existsSysUserAct', { userName: this.sysUserDtos.userName }).then(response => {
                            if (response.code !== 0) {
                                this.$store.dispatch('addSysUserAct', para).then(response => {
                                    this.showAddTable = false
                                    this.roleOpts = []
                                    if (response.code === 0) {
                                        this.$emit('init')
                                        this.$message.success(response.message)
                                        this.cancelApply()
                                    } else {
                                        this.$message.error(response.message)
                                    }
                                    this.$parent.spinning = false
                                }).catch(e => {
                                    this.$parent.spinning = false
                                })
                            } else {
                                this.$parent.spinning = false
                                this.$message.error(response.message)
                            }
                        }).catch(e => {
                            this.$parent.spinning = false
                        })
                    } else {
                        if (this.originalData !== this.sysUserDtos) {
                            value.id = this.id
                            let para = Object.assign({}, this.sysUserDtos)
                            var setUser = this.sysUserDtos.userName
                            let _this = this
                            this.$parent.spinning = true
                            this.$store.dispatch('updSysUserAct', para).then(response => {
                                this.showAddTable = false
                                this.roleOpts = []
                                this.$parent.spinning = false
                                if (response.code === 0) {
                                    this.cancelApply()
                                    let user = sessionStorage.getItem('user')
                                    if (setUser === user) {
                                        sessionStorage.clear()
                                        sessionStorage.setItem('interceptorMsg', '请重新登录！')
                                        setTimeout(function() {
                                            _this.$router.push({
                                                name: 'login'
                                            })
                                        }, 3000)
                                        window.location.reload()
                                    } else {
                                        this.$emit('init')
                                        this.$message.success(response.message)
                                    }
                                } else {
                                    this.$message.error(response.message)
                                }
                            }).catch(e => {
                                this.$parent.spinning = false
                            })
                        } else {
                            this.showAddTable = false
                            this.roleOpts = []
                        }
                    }
                }
            })
        },

        /**
         * Function    : selectedTreeId
         * Description :
         * Input       : val
         * Return      : none
         */
        selectedTreeId(val) {
            this.$refs['orgId'].resetField()
            this.sysUserDtos.orgId = val.id

            /**
             * 级联查询组织机构下的角色
             */
            /*if (this.countOrgChange > 0) {
          this.$store.dispatch('loadOrgsRolesAct',{orgId : val.id}).then(response => {
            this.roleOpts = response;
            this.sysUserDtos.roleId = '';
          });
        }*/
            this.countOrgChange = 1
        },

        /**
         * Function    : cancelApply
         * Description : 取消弹出框
         * Input       : name
         * Return      : none
         */
        cancelApply() {
            this.showAddTable = false
            let _this = this
            setTimeout(function() {
                _this.form.resetFields()
                _this.roleOpts = []
                _this.sex = ''
            }, 100)
        },

        /**
         * Function    : resetUserPasswd
         * Description : 重置用户密码
         * Input       : none
         * Return      : none
         */
        resetUserPasswd(name) {
            this.$parent.spinning = true
            this.$store.dispatch('resetUserPasswdAct', { userName: this.sysUserDtos.userName }).then(response => {
                this.$parent.spinning = false
                if (response.code === 0) {
                    this.$message.success(response.message)
                    this.showAddTable = false
                    this.roleOpts = []
                    this.$refs[name].resetFields()
                } else {
                    this.$message.error(response.message)
                }
            }).catch(e => {
                this.$parent.spinning = false
            })
        }
    },

    created() {}
}
</script>
